const { getApiUrl } = require('../../config/config.js')

Page({
  data: {
    activeTab: 0,     // 当前激活的标签：0-失物 1-招领 2-我的发布
    lostItems: [],    // 失物列表
    foundItems: [],   // 招领列表
    myItems: [],       // 我的发布列表
    loading: false,   // 加载状态
    refreshing: false, // 下拉刷新状态
    hasMore: true,    // 是否还有更多数据
    page: 1,          // 当前页码
    pageSize: 10,     // 每页数量
    categories: [     // 物品分类
      { id: 0, name: '全部' },
      { id: 1, name: '证件卡片' },
      { id: 2, name: '电子产品' },
      { id: 3, name: '钱包钥匙' },
      { id: 4, name: '书籍资料' },
      { id: 5, name: '生活用品' },
      { id: 6, name: '饰品首饰' },
      { id: 7, name: '其他物品' }
    ],
    currentCategory: 0, // 当前选中的分类
    
    // 地点筛选
    locations: [
      { id: 0, name: '全部地点' },
      { id: 1, name: '图书馆' },
      { id: 2, name: '教学楼' },
      { id: 3, name: '食堂' },
      { id: 4, name: '宿舍楼' },
      { id: 5, name: '体育场' },
      { id: 6, name: '校园路上' },
      { id: 7, name: '其他地点' }
    ],
    currentLocation: 0, // 当前选中的地点
    
    searchValue: '',    // 搜索关键词
    isPublishModalVisible: false, // 发布弹窗是否可见
    newItem: {          // 新物品数据
      type: 0,          // 类型：0-失物 1-招领
      category: 1,      // 物品分类ID
      location: 1,      // 地点ID
      name: '',         // 物品名称
      description: '',  // 物品描述
      contactName: '',  // 联系人
      contactPhone: '', // 联系电话
      images: []        // 物品图片
    },
    
    // 筛选条件
    filter: {
      categoryId: 0,
      keyword: ''
    },

    // 图标
    publishIcon: 'https://img.icons8.com/material-outlined/96/ffffff/plus-math.png',
    emptyIcon: 'https://img.icons8.com/clouds/200/000000/search.png',
    publishBtnText: '发布寻物' // 新增发布按钮文本
  },

  onLoad: function() {
    // 初始化发布按钮文本
    this.setData({
      publishBtnText: '发布寻物' // 默认显示寻物标签页
    });
    this.loadData();
  },

  // 加载数据
  loadData(reset = false) {
    if (this.data.loading && !reset) return Promise.reject('已在加载中');
    
    this.setData({ loading: true });

    // 根据当前标签页加载不同数据
    if (this.data.activeTab === 0) {
      return this.loadLostItems();
    } else if (this.data.activeTab === 1) {
      return this.loadFoundItems();
    } else {
      return this.loadMyItems();
    }
  },

  // 加载寻物启事
  loadLostItems() {
    return new Promise((resolve) => {
      // 模拟数据
      setTimeout(() => {
        const mockData = [{
          id: 1,
          type: 'lost',
          title: '丢失学生证',
          description: '在教学楼A区丢失了学生证，是红色的，上面有我的照片和学号。',
          lostTime: '2024-03-18 14:30',
          lostLocation: '教学楼A区',
          status: 0,
          images: ['https://img.icons8.com/color/200/000000/student-card.png'],
          publishTime: '10分钟前',
          userName: '张同学',
          userAvatar: 'https://img.icons8.com/color/96/000000/student-male.png'
        }, {
          id: 2,
          type: 'lost',
          title: '寻找黑色笔记本电脑',
          description: '在图书馆三楼丢失了一台黑色联想笔记本，有明显的贴纸标识。',
          lostTime: '2024-03-18 16:00',
          lostLocation: '图书馆三楼',
          status: 1,
          images: ['https://img.icons8.com/color/200/000000/laptop.png'],
          publishTime: '2小时前',
          userName: '李同学',
          userAvatar: 'https://img.icons8.com/color/96/000000/student-female.png'
        }];

        this.setData({
          lostItems: mockData,
          loading: false,
          hasMore: false
        });
        resolve();
      }, 500);
    });
  },

  // 加载招领启事
  loadFoundItems() {
    return new Promise((resolve) => {
      // 模拟数据
      setTimeout(() => {
        const mockData = [{
          id: 1,
          type: 'found',
          title: '捡到一个蓝色钱包',
          description: '在食堂一楼捡到一个蓝色钱包，内有现金和银行卡。',
          foundTime: '2024-03-18 12:30',
          foundLocation: '食堂一楼',
          currentLocation: '学生会失物招领处',
          status: 0,
          images: ['https://img.icons8.com/color/200/000000/wallet.png'],
          publishTime: '30分钟前',
          userName: '王同学',
          userAvatar: 'https://img.icons8.com/color/96/000000/student-male.png'
        }, {
          id: 2,
          type: 'found',
          title: '捡到一串钥匙',
          description: '在教学楼C区一楼捡到一串钥匙，有校园卡钥匙扣。',
          foundTime: '2024-03-18 09:15',
          foundLocation: '教学楼C区',
          currentLocation: '保安室',
          status: 1,
          images: ['https://img.icons8.com/color/200/000000/key.png'],
          publishTime: '5小时前',
          userName: '李同学',
          userAvatar: 'https://img.icons8.com/color/96/000000/student-female.png'
        }, {
          id: 3,
          type: 'found',
          title: '捡到银色耳机',
          description: '在图书馆二楼自习区捡到一副银色无线耳机，疑似苹果AirPods。',
          foundTime: '2024-03-17 15:40',
          foundLocation: '图书馆二楼',
          currentLocation: '图书馆失物招领处',
          status: 0,
          images: ['https://img.icons8.com/color/200/000000/headphones.png'],
          publishTime: '1天前',
          userName: '赵同学',
          userAvatar: 'https://img.icons8.com/color/96/000000/student-male.png'
        }];

        this.setData({
          foundItems: mockData,
          loading: false,
          hasMore: false
        });
        resolve();
      }, 500);
    });
  },

  // 加载我的发布
  loadMyItems() {
    return new Promise((resolve) => {
      // 模拟数据
      setTimeout(() => {
        const mockData = [{
          id: 1,
          type: 'lost',
          title: '丢失校园卡',
          description: '在体育馆附近丢失了校园卡，急需找回。',
          lostTime: '2024-03-17 15:30',
          lostLocation: '体育馆',
          status: 0,
          images: ['https://img.icons8.com/color/200/000000/id-card.png'],
          publishTime: '1天前',
          userName: '我',
          userAvatar: 'https://img.icons8.com/color/96/000000/student-male.png'
        }, {
          id: 2,
          type: 'found',
          title: '捡到一本教材',
          description: '在阶梯教室捡到一本高等数学教材，有笔记。',
          foundTime: '2024-03-16 10:20',
          foundLocation: '主教学楼',
          currentLocation: '宿舍',
          status: 1,
          images: ['https://img.icons8.com/color/200/000000/study.png'],
          publishTime: '2天前',
          userName: '我',
          userAvatar: 'https://img.icons8.com/color/96/000000/student-male.png'
        }];

        this.setData({
          myItems: mockData,
          loading: false,
          hasMore: false
        });
        resolve();
      }, 500);
    });
  },

  // 切换标签页
  switchTab(e) {
    const tab = parseInt(e.currentTarget.dataset.tab);
    if (this.data.activeTab === tab) return;
    
    this.setData({
      activeTab: tab,
      hasMore: true,
      // 根据当前标签页设置发布按钮文本
      publishBtnText: tab === 0 ? '发布寻物' : tab === 1 ? '发布招领' : '发布'
    });
    this.loadData(true);
  },

  // 返回上一页
  goBack() {
    const pages = getCurrentPages();
    if (pages.length > 1) {
      wx.navigateBack({
        delta: 1
      });
    } else {
      wx.switchTab({
        url: '/pages/index/index'
      });
    }
  },

  // 搜索相关方法
  onSearchInput(e) {
    this.setData({
      'filter.keyword': e.detail.value
    });
  },

  clearSearch() {
    this.setData({
      'filter.keyword': ''
    });
    this.loadData(true);
  },

  doSearch() {
    this.loadData(true);
  },

  // 选择分类
  selectCategory(e) {
    const categoryId = parseInt(e.currentTarget.dataset.id);
    this.setData({
      'filter.categoryId': categoryId
    });
    this.loadData(true);
  },

  // 查看详情
  viewDetail(e) {
    const { id, type } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/lost_found_detail/lost_found_detail?id=${id}&type=${type}`
    });
  },

  // 联系用户
  contactUser(e) {
    const { id } = e.currentTarget.dataset;
    wx.showModal({
      title: '联系方式',
      content: '18888888888（微信同号）',
      showCancel: false
    });
  },

  // 编辑项目
  editItem(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/lost_found_edit/lost_found_edit?id=${id}`
    });
  },

  // 删除项目
  deleteItem(e) {
    const { id } = e.currentTarget.dataset;
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条信息吗？',
      success: (res) => {
        if (res.confirm) {
          const myItems = this.data.myItems.filter(item => item.id !== id);
          this.setData({ myItems });
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },

  // 显示发布模态框
  showPublishModal() {
    // 根据当前标签页设置默认发布类型
    const publishType = this.data.activeTab === 0 ? 'lost' : 'found';
    wx.navigateTo({
      url: `/pages/lost_found_publish/lost_found_publish?type=${publishType}`
    });
  },

  // 下拉刷新
  onPullDownRefresh: function() {
    this.setData({
      refreshing: true,
      page: 1,
      hasMore: true
    });
    
    this.loadData(true).then(() => {
      this.setData({ refreshing: false });
      wx.stopPullDownRefresh();
    }).catch(() => {
      this.setData({ refreshing: false });
      wx.stopPullDownRefresh();
    });
  },

  // 上拉加载更多
  onReachBottom: function() {
    this.loadData();
  },

  // 切换分类
  onCategoryChange: function(e) {
    const id = e.currentTarget.dataset.id;
    if (id === this.data.currentCategory) return;
    
    this.setData({
      currentCategory: id,
      page: 1,
      hasMore: true
    }, () => {
      this.loadData(true);
    });
  },

  // 切换地点
  onLocationChange: function(e) {
    const id = e.currentTarget.dataset.id;
    if (id === this.data.currentLocation) return;
    
    this.setData({
      currentLocation: id,
      page: 1,
      hasMore: true
    }, () => {
      this.loadData(true);
    });
  },

  // 显示/隐藏发布弹窗
  togglePublishModal: function() {
    const visible = !this.data.isPublishModalVisible;
    
    // 重置新物品数据
    if (visible) {
      this.setData({
        newItem: {
          type: this.data.activeTab, // 默认选择当前标签类型
          category: 1,
          location: 1,
          name: '',
          description: '',
          contactName: '',
          contactPhone: '',
          images: []
        }
      });
    }
    
    this.setData({
      isPublishModalVisible: visible
    });
  },
  
  // 更改新物品类型
  changeNewItemType: function(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      'newItem.type': type
    });
  },
  
  // 更改新物品分类
  changeNewItemCategory: function(e) {
    this.setData({
      'newItem.category': Number(e.detail.value) + 1 // 索引+1为实际ID
    });
  },
  
  // 更改新物品地点
  changeNewItemLocation: function(e) {
    this.setData({
      'newItem.location': Number(e.detail.value) + 1 // 索引+1为实际ID
    });
  },
  
  // 输入新物品信息
  inputNewItemInfo: function(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    
    this.setData({
      [`newItem.${field}`]: value
    });
  },
  
  // 上传图片
  uploadImage: function() {
    const count = 3 - this.data.newItem.images.length;
    if (count <= 0) {
      wx.showToast({
        title: '最多上传3张图片',
        icon: 'none'
      });
      return;
    }
    
    wx.chooseImage({
      count,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        // 模拟上传操作
        setTimeout(() => {
          const images = [...this.data.newItem.images, ...res.tempFilePaths];
          this.setData({
            'newItem.images': images
          });
        }, 500);
      }
    });
  },
  
  // 删除已上传图片
  removeImage: function(e) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.newItem.images];
    images.splice(index, 1);
    this.setData({
      'newItem.images': images
    });
  },
  
  // 提交发布信息
  submitNewItem: function() {
    // 表单验证
    const { name, description, contactName, contactPhone } = this.data.newItem;
    if (!name.trim()) {
      wx.showToast({ title: '请输入物品名称', icon: 'none' });
      return;
    }
    if (!description.trim()) {
      wx.showToast({ title: '请输入物品描述', icon: 'none' });
      return;
    }
    if (!contactName.trim()) {
      wx.showToast({ title: '请输入联系人', icon: 'none' });
      return;
    }
    if (!contactPhone.trim()) {
      wx.showToast({ title: '请输入联系电话', icon: 'none' });
      return;
    }
    
    // 模拟提交
    wx.showLoading({ title: '发布中...' });
    
    setTimeout(() => {
      wx.hideLoading();
      
      // 关闭弹窗
      this.setData({
        isPublishModalVisible: false
      });
      
      // 刷新列表
      this.loadData(true);
      
      wx.showToast({
        title: '发布成功',
        icon: 'success'
      });
    }, 1000);
  },
  
  // 标记为已解决
  markAsSolved: function(e) {
    const { id, type } = e.currentTarget.dataset;
    
    wx.showModal({
      title: '标记为已解决',
      content: '确定此物品已找到失主/拾主吗？',
      success: (res) => {
        if (res.confirm) {
          // 模拟标记操作
          const dataKey = type === 0 ? 'lostItems' : 'foundItems';
          const items = [...this.data[dataKey]];
          const index = items.findIndex(item => item.id === id);
          
          if (index !== -1) {
            items[index].isSolved = true;
            
            this.setData({
              [dataKey]: items
            });
            
            wx.showToast({
              title: '已标记为已解决',
              icon: 'success'
            });
          }
        }
      }
    });
  },
  
  // 模拟获取物品数据
  getMockItemsData(page, type, category, location, keyword) {
    const baseData = [];
    const startIndex = (page - 1) * this.data.pageSize;
    
    // 物品类型名称
    const typeName = type === 0 ? '失物' : '招领';
    
    // 模拟数据，根据筛选条件过滤
    for (let i = 0; i < this.data.pageSize; i++) {
      const id = startIndex + i + 1;
      
      // 模拟过滤逻辑
      if (id > 50) break; // 最多50条模拟数据
      
      // 根据类别和地点过滤
      let shouldInclude = true;
      
      if (category > 0 && id % 7 !== category % 7) {
        shouldInclude = false;
      }
      
      if (location > 0 && id % 8 !== location % 8) {
        shouldInclude = false;
      }
      
      // 关键词筛选
      if (keyword && id % 3 !== 0) { // 简单模拟，实际应该检查名称和描述
        shouldInclude = false;
      }
      
      if (!shouldInclude) continue;
      
      // 生成名称
      const categoryName = this.data.categories[id % 7].name;
      const locationName = this.data.locations[id % 8].name;
      const itemNames = [
        '学生证', 'iPhone手机', '校园卡', '钱包', '耳机', '钥匙', '水杯',
        '笔记本电脑', '身份证', '眼镜', '书包', '手表', '雨伞', '外套'
      ];
      
      baseData.push({
        id,
        type, // 0-失物 1-招领
        category: id % 7,
        categoryName,
        location: id % 8,
        locationName,
        name: itemNames[id % itemNames.length],
        description: `这是一个${typeName}的${itemNames[id % itemNames.length]}，在${locationName}附近${type === 0 ? '丢失' : '捡到'}，${type === 0 ? '丢失' : '捡到'}时间大约是昨天下午，请有关人员尽快联系我。`,
        images: [
          '/images/lost_found/item' + (id % 5 + 1) + '.jpg' // 假设有5张示例图
        ],
        createTime: this.getRandomDate(id),
        contactName: '张同学',
        contactPhone: '138****' + (1000 + id),
        isSolved: id % 9 === 0, // 部分标记为已解决
        viewCount: 50 + id * 3
      });
    }
    
    return baseData;
  },
  
  // 生成随机日期
  getRandomDate(id) {
    const now = new Date();
    const days = Math.floor(id % 14); // 0-13天前
    const date = new Date(now);
    date.setDate(date.getDate() - days);
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    return `${year}-${month}-${day}`;
  }
})
